package com.kb5173.search.index.job;

import com.kb5173.search.common.utils.JobLockRedisImpl;
import com.kb5173.search.index.dao.IExpireIndexIdRedisDAO;
import com.kb5173.search.index.service.IIndexService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
* @author Chengfei.Sun
*/
@Component
@Lazy(false)
public class AutoExpireIndexJob {
    protected static final Log log = LogFactory.getLog(AutoExpireIndexJob.class);

    private static final String JOB_ID = "EXPIRE_INDEX_JOB";

    @Autowired
    IExpireIndexIdRedisDAO expireIndexIdRedisDAO;

    @Autowired
    IIndexService indexService;

    @Autowired
    JobLockRedisImpl jobLock;

    /**
     * 描述：根据solr索引的过期时间字段expiredate，定时删除过期的索引
     * 间隔时间：1小时
     */
    @Scheduled(cron="* * 0/1 * * ?")
    public void autoDeleteExpireDocument(){
        log.info("自动扫描过期索引定时器开始");
        Boolean locked = jobLock.lock(JOB_ID);
        if(!locked){
            log.info("上一个扫描过期索引定时器还未执行完成。");
            return;
        }

        try {
            List<String> expireIndexIdList = expireIndexIdRedisDAO.getExpireId();
            if (expireIndexIdList == null || expireIndexIdList.size() == 0) {
                return;
            }
            indexService.deleteDocumentByIds(expireIndexIdList);
            expireIndexIdRedisDAO.deleteExpireId(expireIndexIdList);
        } finally {
            jobLock.unlock(JOB_ID);
        }
        log.info("自动扫描过期索引定时器结束");
    }
}
